package cn.assumejson.springframework.context.context.support;

import cn.assumejson.springframework.beans.context.support.AbstractApplicationContext;
import cn.assumejson.springframework.beans.factory.BeansException;
import cn.assumejson.springframework.beans.factory.config.BeanDefinition;
import cn.assumejson.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import cn.assumejson.springframework.beans.factory.support.BeanDefinitionRegistry;
import cn.assumejson.springframework.beans.factory.support.DefaultListableBeanFactory;
import cn.assumejson.springframework.beans.factory.support.RootBeanDefinition;

import java.util.Map;

/**
 * @author Mr. Li
 * @version 1.0
 * @since 1.0 2021/12/4 18:12
 */
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {

    private final DefaultListableBeanFactory beanFactory;

    public GenericApplicationContext() {
        this.beanFactory = new DefaultListableBeanFactory();
    }

    @Override
    protected void refreshBeanFactory() throws BeansException {

    }

    @Override
    public Class<?> getType(String name) {
        return this.beanFactory.getBeanDefinition(name).getBeanClass();
    }

    @Override
    public ConfigurableListableBeanFactory getBeanFactory() {
        return this.beanFactory;
    }

    @Override
    public RootBeanDefinition registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        return this.beanFactory.registerBeanDefinition(beanName, beanDefinition);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
        return this.beanFactory.getBeanDefinition(beanName);
    }

    @Override
    public String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
        if (includeNonSingletons && allowEagerInit) {
            return doGetBeanNamesForType(type);
        }
        return doGetBeanNamesForType(type);
    }

    private String[] doGetBeanNamesForType(Class<?> type) {
        Map<String, ?> beansOfType = this.getBeansOfType(type);
        return (String[]) beansOfType.keySet().toArray();
    }
}
